//Copyright (C) 2010 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

/*
 * MainFrame.java
 *
 * Created on Nov 11, 2010, 2:36:02 PM
 */

package org.workplicity.cia.ui;

import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.workplicity.cia.table.ElogsTableModel;
import org.workplicity.cia.table.HandoffsTableModel;
import org.workplicity.cia.table.render.ElogsTableRenderer;
import org.workplicity.cia.table.render.HandoffsTableRenderer;
import org.workplicity.cia.util.CIAHelper;
import org.workplicity.cia.util.Pair;
import org.workplicity.cia.worklet.ElogsWorklet;
import org.workplicity.elog.entry.Elog;
import org.workplicity.elog.entry.Elog.Status;
import org.workplicity.elog.entry.Elog.Type;
import org.workplicity.elog.entry.ElogUser;
import org.workplicity.elog.entry.Handoff;
import org.workplicity.task.NetTask;
import org.workplicity.util.Helper;
import org.workplicity.util.Resources;
import org.workplicity.worklet.WorkletContext;

/**
 * This class implements the main frame for the elogger.
 * @author Ron Coleman
 */
public class MainFrame extends javax.swing.JFrame {
    private ElogUser user = null;

    private ElogsWorklet worklet = ElogsWorklet.getInstance();

    private WorkletContext context = worklet.getContext();

    private ArrayList<ElogUser> users;

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();

        // Position the dialog
        this.setLocationRelativeTo(null);

        user = (ElogUser) Helper.whoAmI(context);

        if(!CIAHelper.isManagement(user))
            this.adminMenu.setEnabled(false);

        this.setTitle("Netlog (" + user.getLogname() + ")");

        this.setIconImage(Resources.logoSmall.getImage());

        init();
    }

    private void init() {
        // Load the users and trades cache
        ElogsWorklet.getInstance().getUsersCache().refresh();
        ElogsWorklet.getInstance().getTrades().refresh();
        
        // Set the view
        this.viewTextField.setText(user.getFunction().toString());
       
        // Load the table with the logs
        initElogTable();
    }

    private void initElogTable() {
        // Format the table for L&F
        formatElogsTable();

        // Format the handoff table for L&F
        formatHandoffTable();

        // Load the users combo box and make the selected one me
        users = Helper.query(NetTask.REPOS_ACCOUNTS, "/list", context);

        if(users == null)
            return;

        Collections.sort(users, new Comparator() {
            public int compare(Object o1, Object o2) {
                String u1 = ((ElogUser) o1).getLogname();
                String u2 = ((ElogUser) o2).getLogname();
                return u1.compareTo(u2);
            }
        });
        
        ElogUser me = (ElogUser) Helper.whoAmI(context);

        ElogUser defaultUser = me;

        for (ElogUser auser : users) {
            if(auser.getLogname().equals("system"))
                continue;

            usersComboBox.addItem(auser);
            
            if (auser.getLogname().equals(me.getLogname())) {
                defaultUser = auser;
            }
        }

        usersComboBox.setSelectedItem(defaultUser);

        this.typeComboBox.addItem(Elog.Type.ANY);
        this.typeComboBox.addItem(Elog.Type.NORMAL);
        this.typeComboBox.addItem(Elog.Type.UNUSUAL);

        this.statusComboBox.addItem(Elog.Status.ANY);
        this.statusComboBox.addItem(Elog.Status.NOTDONE);
        this.statusComboBox.addItem(Elog.Status.DONE);

        this.ageComboBox.removeAllItems();
        for(int i=0; i < CIAHelper.AGES.length; i++)
            this.ageComboBox.addItem(CIAHelper.AGES[i]);

        ageComboBox.setSelectedIndex(CIAHelper.AGE_DEFAULT);

        // Load the elogsModel data into the table
        loadModel();

        loadHandoffsModel();
    }

    private void formatHandoffTable()
    {
        final int[] WIDTHS = {
             40,  // Id
            100,  // Update date
             75,  // From
             75,  // To
             75,  // Trade
            241   // Description
        };

        for(int i=0; i < WIDTHS.length; i++) {
            TableColumn col = handoffsTable.getColumnModel().getColumn(i);

            col.setPreferredWidth(WIDTHS[i]);
        }

        TableColumnModel cm = this.handoffsTable.getColumnModel();

        HandoffsTableRenderer cr = new HandoffsTableRenderer();

        for (int i = 0; i < handoffsTable.getColumnCount(); i++) {
            cm.getColumn(i).setCellRenderer(cr);
        }

        // Add mouse support for the request table
        // See http://mycodepage.blogspot.com/2006/09/how-to-create-double-click-event-on.html
        handoffsTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    JTable target = (JTable) e.getSource();

                    final int row = target.getSelectedRow();

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            editHandoff(row);
                        }
                    });
                }
            }
        });
    }

    /**
     * Formats the table for L&F
     */
    private void formatElogsTable() {
        // The code below left justified the columns
        // but they dont have the L&F of the default
        // settings
//        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
//        renderer.setHorizontalAlignment(SwingConstants.LEFT);
//        elogTable.getColumn(elogTable.getColumnName(1)).setHeaderRenderer(renderer);

        elogsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        final int[] WIDTHS = {
             40,  // Log id
            100,  // Update date
             75,  // User
             75,  // Type
             75,  // Status
            241   // Description
        };

        for(int i=0; i < WIDTHS.length; i++) {
            TableColumn col = elogsTable.getColumnModel().getColumn(i);

            col.setPreferredWidth(WIDTHS[i]);
        }

        TableColumnModel cm = this.elogsTable.getColumnModel();

        ElogsTableRenderer cr = new ElogsTableRenderer();

        for (int i = 0; i < elogsTable.getColumnCount(); i++) {
            cm.getColumn(i).setCellRenderer(cr);
        }

        // Add mouse support for the request table
        // See http://mycodepage.blogspot.com/2006/09/how-to-create-double-click-event-on.html
        elogsTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    JTable target = (JTable) e.getSource();
                    
                    final int row = target.getSelectedRow();

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            editEntry(row);
                        }
                    });
                }
            }
        });
    }

    /**
     * Loads the handoffs into the table.
     */
    private void loadHandoffsModel() {
        HandoffsTableModel model = (HandoffsTableModel) this.handoffsTable.getModel();
        model.refresh(user);
    }

    /**
     * Loads the elogsModel with all the relevant data to query
     * the repository.
     */
    private void loadModel() {
        // Set up the filters
        loadModelAge();

        ElogUser selectedUser = (ElogUser) this.usersComboBox.getSelectedItem();
        ElogsTableModel model = (ElogsTableModel) elogsTable.getModel();
        model.setType((Type) this.typeComboBox.getSelectedItem());

        model.setStatus((Status) this.statusComboBox.getSelectedItem());

        model.setView(selectedUser.getFunction());

        // Tell the elogsModel to retrive data per the filters
        model.refresh(user);
    }

    /**
     * Sets up the age filters in the elogsModel.
     * @param elogsModel Table elogsModel
     */
    private void loadModelAge() {
        int age = this.ageComboBox.getSelectedIndex();

        String key = CIAHelper.AGES[age];

        HashMap<String,Pair<Long,Long>> map = CIAHelper.getAgeMap();

        Long starts = map.get(key).getStarts();
        Long ends = map.get(key).getEnds();
        
        ElogsTableModel elogsModel = (ElogsTableModel) elogsTable.getModel();
        elogsModel.setStart(starts);
        elogsModel.setEnd(ends);

        HandoffsTableModel handoffsModel = (HandoffsTableModel) handoffsTable.getModel();
        handoffsModel.setStart(starts);
        handoffsModel.setEnd(ends);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        elogsTable = new javax.swing.JTable();
        byeButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        typeComboBox = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        statusComboBox = new javax.swing.JComboBox();
        addButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        usersComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        ageComboBox = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        handoffsTable = new javax.swing.JTable();
        viewTextField = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem2 = new javax.swing.JCheckBoxMenuItem();
        jCheckBoxMenuItem3 = new javax.swing.JCheckBoxMenuItem();
        editMenut = new javax.swing.JMenu();
        jCheckBoxMenuItem4 = new javax.swing.JCheckBoxMenuItem();
        adminMenu = new javax.swing.JMenu();
        usersMenuItem = new javax.swing.JCheckBoxMenuItem();
        tradesMenuItem = new javax.swing.JCheckBoxMenuItem();
        toolsMenu = new javax.swing.JMenu();
        searchMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setText("View:");

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Logs", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N

        elogsTable.setFont(new java.awt.Font("Tahoma", 0, 12));
        elogsTable.setModel(new org.workplicity.cia.table.ElogsTableModel());
        jScrollPane1.setViewportView(elogsTable);

        byeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bye2.png"))); // NOI18N
        byeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                byeButtonActionPerformed(evt);
            }
        });

        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setText("Type:");

        typeComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        typeComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                typeComboBoxItemStateChanged(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel3.setText("Status");

        statusComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        statusComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                statusComboBoxItemStateChanged(evt);
            }
        });

        addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/add2.png"))); // NOI18N
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setText("User:");

        usersComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        usersComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                usersComboBoxItemStateChanged(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel5.setText("Age:");

        ageComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        ageComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<= 24 hours", "<= 48 hours", "<= 1 week", "<= 30 days", "> 30 & <= 60 days", "> 60  & <= 90 days", "> 90 & <= 180 days", "> 180 & <= 365 days", "> 1 year" }));
        ageComboBox.setSelectedIndex(2);
        ageComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                ageComboBoxItemStateChanged(evt);
            }
        });

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Handoffs", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N

        handoffsTable.setFont(new java.awt.Font("Tahoma", 0, 12));
        handoffsTable.setModel(new HandoffsTableModel( ));
        jScrollPane2.setViewportView(handoffsTable);

        viewTextField.setEditable(false);
        viewTextField.setFont(new java.awt.Font("Tahoma", 1, 12));

        jMenuBar1.setFont(new java.awt.Font("Tahoma", 0, 14));

        fileMenu.setText("File");
        fileMenu.setFont(new java.awt.Font("Comic Sans MS", 0, 14));

        jCheckBoxMenuItem1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jCheckBoxMenuItem1.setSelected(true);
        jCheckBoxMenuItem1.setText("Export...");
        fileMenu.add(jCheckBoxMenuItem1);

        jCheckBoxMenuItem2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jCheckBoxMenuItem2.setSelected(true);
        jCheckBoxMenuItem2.setText("Print...");
        fileMenu.add(jCheckBoxMenuItem2);

        jCheckBoxMenuItem3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jCheckBoxMenuItem3.setSelected(true);
        jCheckBoxMenuItem3.setText("Bye");
        fileMenu.add(jCheckBoxMenuItem3);

        jMenuBar1.add(fileMenu);

        editMenut.setText("Edit");
        editMenut.setFont(new java.awt.Font("Comic Sans MS", 0, 14));

        jCheckBoxMenuItem4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jCheckBoxMenuItem4.setSelected(true);
        jCheckBoxMenuItem4.setText("Find...");
        editMenut.add(jCheckBoxMenuItem4);

        jMenuBar1.add(editMenut);

        adminMenu.setText("Admin");
        adminMenu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        usersMenuItem.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        usersMenuItem.setSelected(true);
        usersMenuItem.setText("Users");
        usersMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usersMenuItemActionPerformed(evt);
            }
        });
        adminMenu.add(usersMenuItem);

        tradesMenuItem.setFont(new java.awt.Font("Tahoma", 0, 14));
        tradesMenuItem.setSelected(true);
        tradesMenuItem.setText("Trades");
        tradesMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tradesMenuItemActionPerformed(evt);
            }
        });
        adminMenu.add(tradesMenuItem);

        jMenuBar1.add(adminMenu);

        toolsMenu.setText("Tools");
        toolsMenu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        searchMenuItem.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        searchMenuItem.setText("Search");
        searchMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchMenuItemActionPerformed(evt);
            }
        });
        toolsMenu.add(searchMenuItem);

        jMenuBar1.add(toolsMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(viewTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(usersComboBox, 0, 134, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 298, Short.MAX_VALUE)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(byeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(viewTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(statusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(usersComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(byeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(refreshButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(ageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void usersMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usersMenuItemActionPerformed
        final JFrame frame = this;
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final UsersDialog dialog = new UsersDialog(frame);

                dialog.setVisible(true);
            }
        });
    }//GEN-LAST:event_usersMenuItemActionPerformed

    private void tradesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tradesMenuItemActionPerformed
        final JFrame frame = this;
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final TradesDialog dialog = new TradesDialog(frame);

                dialog.setVisible(true);
            }
        });
    }//GEN-LAST:event_tradesMenuItemActionPerformed

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        editEntry(-1);
                    }
                });
            }
        });
    }//GEN-LAST:event_addButtonActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                loadModelAge();
                
                ElogsTableModel model = (ElogsTableModel) elogsTable.getModel();
                model.refresh(user);

                HandoffsTableModel modelHandoffs = (HandoffsTableModel) handoffsTable.getModel();
                modelHandoffs.refresh(user);
            }
        });

    }//GEN-LAST:event_refreshButtonActionPerformed

    private void byeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_byeButtonActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // this line is commented out because it crashes the program
                // need to ask Ron about this
                //winClose();

                dispose();
            }

        });
    }//GEN-LAST:event_byeButtonActionPerformed

    private void ageComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_ageComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        loadModelAge();

        refresh();
    }//GEN-LAST:event_ageComboBoxItemStateChanged

    private void usersComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_usersComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        this.user = (ElogUser) this.usersComboBox.getSelectedItem();

        refresh();
    }//GEN-LAST:event_usersComboBoxItemStateChanged

    private void typeComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_typeComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        Type type = (Type) this.typeComboBox.getSelectedItem();

        ElogsTableModel elogsModel = (ElogsTableModel) elogsTable.getModel();
        elogsModel.setType(type);

        refresh();
    }//GEN-LAST:event_typeComboBoxItemStateChanged

    private void statusComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_statusComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        Status status = (Status) this.statusComboBox.getSelectedItem();

        ElogsTableModel elogsModel = (ElogsTableModel) elogsTable.getModel();
        elogsModel.setStatus(status); 

        refresh();
    }//GEN-LAST:event_statusComboBoxItemStateChanged

    private void searchMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchMenuItemActionPerformed
        //
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final SearchGUI dialog = new SearchGUI();

                dialog.setVisible(true);
            }
        });
    }//GEN-LAST:event_searchMenuItemActionPerformed

    private void refresh() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ElogsTableModel elogsModel = (ElogsTableModel) elogsTable.getModel();
                elogsModel.refresh(user);

                HandoffsTableModel handoffsModel = (HandoffsTableModel) handoffsTable.getModel();
                handoffsModel.refresh(user);
            }
        });
    }

    /**
     * Opens the elog entry associated with this handoff.
     * @param row Row
     */
    private void editHandoff(int row) {
        HandoffsTableModel handoffsModel = (HandoffsTableModel) handoffsTable.getModel();

        Handoff handoff = handoffsModel.getRow(row);

        Elog elog = (Elog) Helper.fetch(handoff.getReposTitle(), handoff.getElogId(), context);

        ElogUser owner = CIAHelper.toUser(handoff.getFromId());

        ElogEditDialog dialog = new ElogEditDialog(this,owner,elog);

        dialog.setVisible(true);
//        HandoffPopupDialog2 dialog = new HandoffPopupDialog2(this,handoff);
//
//        dialog.setVisible(true);
//
//        // Refresh the display
//        this.loadModelAge();
//
//        ElogsTableModel elogsModel = (ElogsTableModel) elogsTable.getModel();
//        elogsModel.refresh(user);
//
//        handoffsModel.refresh(user);
    }

    /**
     * Opens the elog edit dialog given a row, if there is one
     * or creates a new elog.
     * @param row Row
     */
    private void editEntry(int row) {
        Elog elog = null;

        ElogsTableModel elogsModel = (ElogsTableModel) elogsTable.getModel();

        ElogUser owner = null;

        if(row != -1)
        {
            elog = elogsModel.getRow(row);
            owner = CIAHelper.toUser(elog.getReposTitle());
        }
        else
        {
            elog = new Elog();
            owner = (ElogUser) Helper.whoAmI(WorkletContext.getInstance());
        }

        ElogEditDialog dialog = new ElogEditDialog(this, owner, elog);

        dialog.setVisible(true);

        // Refresh the display
        this.loadModelAge();

        elogsModel.refresh(user);

        HandoffsTableModel handoffsModel = (HandoffsTableModel) handoffsTable.getModel();
        handoffsModel.refresh(user);
    }

    /**
     * Invokes the window close procedure.
     */
    public void winClose() {
        Helper.logout(user, context);
    }

    /**
     * Runs the main method when launched from the deskotp or
     * as a worklet.
     * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {

                }

                final MainFrame frame = new MainFrame();

                frame.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        frame.winClose();

                        System.exit(0);
                    }
                });

                frame.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JMenu adminMenu;
    private javax.swing.JComboBox ageComboBox;
    private javax.swing.JButton byeButton;
    private javax.swing.JMenu editMenut;
    private javax.swing.JTable elogsTable;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JTable handoffsTable;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem2;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem3;
    private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton refreshButton;
    private javax.swing.JMenuItem searchMenuItem;
    private javax.swing.JComboBox statusComboBox;
    private javax.swing.JMenu toolsMenu;
    private javax.swing.JCheckBoxMenuItem tradesMenuItem;
    private javax.swing.JComboBox typeComboBox;
    private javax.swing.JComboBox usersComboBox;
    private javax.swing.JCheckBoxMenuItem usersMenuItem;
    private javax.swing.JTextField viewTextField;
    // End of variables declaration//GEN-END:variables

}
